import { Props } from "@/components/form_item/formItemConfig"
import InputVerificationCode from "@/components/form_item/InputVerificationCode"
import styled from "@emotion/styled"
import { RefObject } from "react"
import { Control, Controller } from "react-hook-form"
import Svg from "../base/Svg"

type CodeProps = Props & {
    control?: Control
    callBackSubmit?: () => void
    ref?: RefObject<unknown>
    autoSubmit?: boolean
}

//这是InputVerificationCode 整合进入react-hook-form的用法
export const InputCode = ({
    fieldName,
    control,
    callBackSubmit,
    ref,
    className = "",
    style,
    autoSubmit = true,
}: CodeProps) => {
    return (
        <Controller
            name={fieldName}
            control={control}
            rules={{
                required: "Please enter the correct code",
            }}
            render={({ field: { onChange, onBlur, value }, formState, fieldState }) => {
                const errorsName = formState.errors[fieldName]
                return (
                    <>
                        <InputVerificationCode
                            ref={ref}
                            className={className}
                            style={style}
                            onChangeCode={onChange}
                            callBackSubmit={callBackSubmit}
                            autoSubmit={autoSubmit}
                        />
                        {errorsName && errorsName.type === "manual" && (
                            <VerifyMessage className={`codemsg error`}>
                                <em>
                                    <Svg src={"components/form_item/public_fail_icon.svg"} />
                                </em>
                                {(errorsName?.message as string) || "Please enter the correct code"}
                            </VerifyMessage>
                        )}
                    </>
                )
            }}
        />
    )
}

export default InputCode

const VerifyMessage = styled.p`
    display: none;
    position: absolute;
    bottom: -32rem;
    left: 0;
    font-family: "Gilroy", sans-serif;
    font-weight: 400;
    font-size: 12rem;
    line-height: 16rem;
    letter-spacing: 0;
    color: #fb2d60;
    padding-left: 20rem;

    & > em {
        position: absolute;
        display: block;
        width: 16rem;
        height: 16rem;
        top: 0;
        left: 0;
        line-height: normal;
        text-align: center;
    }

    &.stepNextvm {
        display: block;
        position: initial;
        margin: 0;
        padding: 0;
    }

    &.stepNextvm::before {
        display: none;
    }

    &.codemsg {
        position: relative;
        margin: 0;
        bottom: -4rem;
        left: 0;
    }

    &.codemsg.error {
        display: block;
    }
`
